<template>
  <div class="upload-file">
    <!-- 创建一个表单，用于提交文件数据 -->
    <form id="uploadForm" enctype="multipart/form-data" method="post" action="/batchUploadFile">
      <!-- 创建一个文件选择器，用于选择多个epub格式的文件 -->
      <input id="fileInput" type="file" name="file" multiple accept=".epub" @change="handleFileChange" />
      <!-- 创建一个按钮，用于提交表单 -->
      <button type="submit" @click.prevent="handleSubmit">上传到服务器</button>
    </form>
    <!-- 创建一个容器，用于显示已选择文件的封面 -->
    <div class="cover-container">
      <!-- 使用v-for指令遍历已选择文件列表，生成每个封面 -->
      <div v-for="(file, index) in fileList" :key="index" class="cover-item">
        <!-- 使用img标签显示封面图片，使用epub.js获取EPUB文件的封面 -->
        <img :src="file.cover" alt="封面" />
        <!-- 显示文件名和大小 -->
        <p>{{ file.name }} ({{ file.size }})</p>
        <!-- 创建一个按钮，用于删除某个文件 -->
        <button @click="handleDelete(index)">删除</button>
      </div>
    </div>
  </div>
</template>

<script>
// 导入epub.js库
import ePub from 'epubjs'

export default {
  data() {
    return {
      fileList: []
    }
  },
  methods: {
    handleFileChange(event) {
      let files = event.target.files
      for (let i = 0; i < files.length; i++) {
        let file = files[i]
        let fileType = file.name.substring(file.name.lastIndexOf('.') + 1)
        if (!fileType.equalsIgnoreCase('epub')) {
          this.$message.error('只能上传epub格式的文件')
          continue
        }
        let fileSize = file.size / 1024 / 1024
        if (fileSize > 100) {
          this.$message.error('单个文件大小不能超过100MB')
          continue
        }
        let book = ePub(file)
        book.loaded.metadata.then((metadata) => {
          book.coverUrl().then((cover) => {
            file.cover = cover
            this.fileList.push(file)
          })
        })
      }
    },
    handleSubmit() {
      let form = document.getElementById('uploadForm')
      let formData = new FormData(form)
      formData.append('token', this.$store.state.token)
      this.post('/uploadBinary', formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      }).then((response) => {
        let ret = response.data
        if (response.status === 200) {
          this.alert(ret.msg, { type: 'success', placement: 'top' })
          this.fileList = []
          document.getElementById('file').value = ''
        } else {
          this.alert(ret.msg, { type: 'success', placement: 'top' })
        }
      })
    },
    handleDelete(index) {
      this.fileList.splice(index, 1)
      let newFileList = new FileList()
      for (let i = 0; i < this.fileList.length; i++) {
        newFileList.push(this.fileList[i])
      }
      document.getElementById('file').files = newFileList
    }
  }
}
</script>

<style lang='scss' scoped></style>
